package org.pictual.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Vector;

import javax.swing.ImageIcon;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.log4j.Logger;
import org.lwjgl.opengl.InputImplementation;
import org.pictual.util.ConstantsKeys;
import org.pictual.util.gsearch.Client;
import org.pictual.util.gsearch.Result;


public class GoogleSearchImg {

	protected static Logger log= Logger.getLogger(GoogleSearchImg.class);
	
	private static MyImage extractSingleImg(Result r) {

		try {

			String imageName = r.getUrl();
			URL imageURL;

			imageURL = new URL(imageName);


			ImageIcon icon = new ImageIcon(imageURL); 

			float w=icon.getIconWidth();
			float h=icon.getIconHeight();

			float dif = 0;
			if(w > 150){
				dif = 150 / w;
				w = 150;           
				h = h * dif;
				if(h > 150){
					dif = 150 / h;
					h = 150;
					w = w * dif;
				}

			} else if(h > 150){
				dif = 150 / h;
				h = 150;
				w = w * dif;
			}
			//href= imgRef (LA ORIGINAL), imgLink (LA COPIA EN PICTUAL) , thumbnail= (miniatura) NUEVA SRC
			MyImage image = new MyImage(r.getUrl(), r.getUrl(), r.getUrl(), new Integer((int) w), new Integer((int) h));
			return image;
		} catch (MalformedURLException e) {
			log.error("MalformedURLException");
		}
		return null;
	}
	
	public static Vector<MyImage> queryForImages(String query, String idioma){

		Vector<MyImage> images= new Vector<MyImage>();
		try{
			Client client = new Client();
			client.setIdioma(idioma);

			List<Result> resultImages= client.searchImages(query);
			int i=1;
			for(Result r: resultImages){
				if(i==7) break;
				String url=r.getUrl();
				log.info("URL de la imagen: "+url);
				
//				DescargaImagen di = new DescargaImagen(url);
//				String urlLocal=di.processDownload(query, i++);
				
				String urlLocal=DescargaImagen.uploadImageByFTP(url, query+i, "jpg");
				
				if(urlLocal!=null){	//Si la imagen esta en el ftp
					MyImage img=extractSingleImg(r);
					img.setImgLink(ConstantsKeys.URL_PICTUAL+urlLocal);
					log.info("link: "+img.getImgLink());
					log.info("href: "+img.getImgRef());
					//TODO Redimensionar y guardar
					
						
							try {
								
								log.info("RUTA IMAGEN: http://www.pictual.org"+urlLocal);
								URL fileUri = new URL("http://www.pictual.org"+urlLocal);    
								int startIndex = fileUri.toString().lastIndexOf('/');
								String fileName = fileUri.toString().substring(startIndex + 1);
								log.info("fileName: "+fileName);
//								
								DescargaImagen.uploadThumbnailByFTP(
										"http://www.pictual.org"+urlLocal, 
										query+i+"_thumbnail", 
										img.getWidth(), 
										img.getHeight(), "jpg");
//								
							} catch (IOException e) {
								log.error("Error en el fichero", e);
							}
					String thumbnail = ConstantsKeys.URL_PICTUAL+ConstantsKeys.PATH_IMAGES+"/"+query+i+"_thumbnail.jpg";
					
					img.setImgThumbnail(thumbnail);
					log.info("thumbnail: "+img.getImgThumbnail());
					
					i++;	//guardo la imagen
					log.info("Se descargo bien y se guarda");
					images.add(img);
				}
				
			}
		}catch(Exception e){
			log.error("FALLO EN queryForImages", e);
		}
		
		return images;
	}
}
